import React, { Component } from "react";
import { SafeAreaView, Text, View, StyleSheet, TouchableOpacity, Image, TextInput, PermissionsAndroid, Platform, DeviceEventEmitter, Switch, FlatList, ActivityIndicator } from 'react-native';
import Constant from '../../../utils/Constant'//全局变量
import { getImgUrl, getCarRegisterDate, getMileFormat, getPriceFormat, getStoreStatus, getSaleStatus, getCheckStatus, getPurchaseType } from '../../../utils/ComFunction';
import HttpUtils from "../../../utils/HttpUtils";
import HttpUrls from "../../../utils/HttpUrls";
import Header from "../../../components/header";
import { ToastToUser } from "../../../utils/CustomToast";
import ActionSheet from 'react-native-actionsheet'
import ImageCropPicker from 'react-native-image-crop-picker';
import Upload from '../../../components/upload/Upload'
import { requestCameraPermission, requestWritePermission } from '../../../utils/Permission';
import Loading from "../../../utils/Loading";
import AndroidModule from "../../../utils/AndroidConnent";
import CommonDialog from "../../../components/dialog/CommonDialog";
const isAndroid = Platform.OS == 'android';
import DeviceInfo from 'react-native-device-info';
import AsyncImage from '../../../components/image/AsyncImage'


let navigation = null

export default class SelectShareCarListPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            carList: [],
            pageNo: 1,
            showFoot: 0,
            carSearchParams: {},
            maxCount: this.props.route.params.maxCount ? this.props.route.params.maxCount : 8,
            alreadyCount: 0,
            fromPage: this.props.route.params.fromPage,
        };
    }

    componentDidMount() {
        navigation = this.props.navigation;
        this.initData()
    }

    initData() {
        if (this.props.route && this.props.route.params) {
            let params = this.props.route.params;

            this.setState({
                carSearchParams: params.searchParams
            }, function () {
                this.getCarList()
            })
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'选择车辆'} ></Header>

                <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: 15, marginTop: 10 }}>
                    <Text>您已选择{this.state.alreadyCount}辆车</Text>
                    <Text>{this.state.alreadyCount}/{this.state.maxCount}</Text>
                </View>

                {this.renderCarList()}

                <View
                    style={[styles.bottomTabContainer, { marginBottom: Constant.bottomHeight }]}>

                    <TouchableOpacity
                        style={styles.confirmBtn}
                        onPress={() => {
                            this.confirmSelectCar()
                        }}>
                        <Text style={styles.btnText}>{this.getBtnText()}</Text>
                    </TouchableOpacity>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }

    confirmSelectCar() {
        if (this.state.fromPage == 'MessageChat') {

            let result = null
            this.state.carList.forEach((item) => {
                if (item.isCheck) {
                    result = item
                }
            })
            let carInfo = {
                carId: result.carId,
                carTitle: result.seriesName + ' ' + result.speciesName,
                carPrice: this.getCarPrice(result),
                mainPic: getImgUrl(result.mainPic),
                mile: getMileFormat(result.mileage),
                registerDate: getCarRegisterDate(result.registerDate),
                merchantId: result.merchantId + ''
            }

            DeviceEventEmitter.emit('selectCarResultListener', carInfo);
            navigation.goBack()
        } else {
            if (this.state.alreadyCount <= 0) {
                ToastToUser('请选择分享的车辆')
                return
            }
            try {
                let selectCars = []
                this.state.carList.map((item)=>{
                    if (item.isCheck) {
                        selectCars.push(item)
                    }
                })
                AndroidModule.sharePlatFormCarListImages({selectCars: selectCars, shareOwnerMerchant: this.state.fromPage != 'StrictCarListPage' ? true:false,companyInfo:Constant.companyInfo})
            } catch (error) {

            }
        }
    }

    getBtnText() {
        if (this.state.fromPage == 'MessageChat') {
            return '发送车辆'
        } else {
            return '下一步'
        }
    }

    renderCarList() {
        return (
            <FlatList
                data={this.state.carList}
                renderItem={this.renderCarItem.bind(this)}
                keyExtractor={item => item.carId + ''}
                style={styles.list}
                extraData={this.state}
                ListFooterComponent={this._renderFooter.bind(this)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={0.2}

                ListEmptyComponent={this.renderEmpty.bind(this)}

            />
        )
    }

    renderCarItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    if (this.isMaxCount() && !item.isCheck) {
                        ToastToUser('最多选择' + this.state.maxCount + '辆车辆')
                        return
                    }
                    this.selectCar(item, index)
                }}
            >
                <View style={styles.carContainer}>

                    {item.isCheck ? <Image style={styles.checkIcon} source={require('source/image/icon_selector_checked.png')}></Image> :
                        <Image style={styles.checkIcon} source={require('source/image/icon_selector_unchecked.png')}></Image>
                    }


                    <AsyncImage
                        source={{ uri: getImgUrl(item.mainPic) }}
                        defaultSource={require('source/image/icon_car_default.png')}
                        style={styles.carImage}
                        resizeMode="cover"
                    />

                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={2} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>


                        <Text style={styles.price}>{this.getCarPrice(item)}</Text>

                    </View>
                </View>


            </TouchableOpacity>
        )

    }

    isMaxCount() {
        let count = 0
        for (let i = 0; i < this.state.carList.length; i++) {
            if (this.state.carList[i].isCheck) {
                count++

            }
        }

        return count >= this.state.maxCount
    }

    selectCar(item, index) {
        let carList = JSON.parse(JSON.stringify(this.state.carList))
        for (let i = 0; i < carList.length; i++) {
            if (i == index) {
                carList[i].isCheck = !carList[i].isCheck
            }
        }

        let alreadyCount = this.state.alreadyCount
        if (carList[index].isCheck) {
            alreadyCount++
        } else {
            alreadyCount--
        }

        this.setState({
            carList: carList,
            alreadyCount: alreadyCount
        })
    }

    getCarPrice(item) {
        //联盟商家车源显示“一口价”，加盟商车源显示“展厅标价” 
        //isFranchisee：是否加盟商 0否1是 

        return getPriceFormat(item.markedPrice)
    }

    getSubCarInfo(item) {

        if (item.carType == 1) {//新车

            return '新车指导价：' + getPriceFormat(item.guidePrice)
        } else {
            return getCarRegisterDate(item.registerDate) + ' ' + getMileFormat(item.mileage)
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    _onEndReached() {
        if (this.state.carList.length == 0) {
            return
        }
        console.log('_onEndReached', this.state.showFoot)
        if (this.state.showFoot != 0) {
            return null;
        }

        let nextPage = this.state.pageNo + 1

        this.setState({ showFoot: 2, pageNo: nextPage },
            function () {
                this.getCarList();
            });


    }

    _renderFooter() {
        if (this.state.carList.length == 0) {
            return null
        }
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    getCarList() {

        let requestParams = this.state.carSearchParams
        requestParams.pageNo = this.state.pageNo

        HttpUtils.postRequest(HttpUrls.searchCars, requestParams)
            .then((result) => {

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList
                    if (resultList && resultList.length > 0) {

                        if (resultList.length < 20) {

                            this.setState({
                                showFoot: 1
                            })
                        } else {
                            this.setState({
                                showFoot: 0
                            })
                        }

                        this.setState({
                            carList: this.state.carList.concat(resultList),
                        })

                    } else {

                        this.setState({
                            showFoot: 1
                        })
                    }

                }
            })
            .catch((error) => {

            });
    }



}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',

    },

    bottomTabContainer: {
        height: 50,
        width: '100%',

        flexDirection: 'row',
        alignItems: 'center',

        backgroundColor: '#fff'
    },
    resetBtn: {
        flex: 1,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    confirmBtn: {
        flex: 2,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#ffde00'
    },
    btnText: {
        fontSize: 16,
        color: '#333333',
    },

    cardContainer: {
        backgroundColor: '#fff',
        marginTop: 10,
        paddingLeft: 15,
        paddingRight: 15,
        paddingTop: 10,
        paddingBottom: 10,
        flexDirection: 'column',
    },
    carContainer: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    carImage: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f5f5f5',
    },
    infoContainer: {
        flex: 1,
        marginLeft: 10,
        height: 90,
        flexDirection: 'column',
        justifyContent: 'space-between'
    },
    carName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 5,
        color: '#333',
    },
    subInfo: {
        fontSize: 12,
        color: '#999999',
        marginTop: 3,
    },
    price: {
        fontSize: 14,
        color: '#ED542E',

    },

    checkIcon: {
        width: 20,
        height: 20,
        marginRight: 10,
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },


})